//
//  StatusCell.swift
//  weibo_swift
//
//  Created by dulinlong on 15/7/4.
//  Copyright © 2015年 sheji_56. All rights reserved.
//

import UIKit
import SDWebImage
import FFAutoLayout

//转发微博cell
let StatusForwardCellIndentifer = "StatusForwardReuseIndentifer"
//原创微博cell
let StatusNormalCellIndentifier = "StatusNormalReuseIndentifier"
//配图cell标示
private let PictureCellIndentifier = "PictureCellReuseIndentifier"

//屏幕宽度
let screenWidth = UIScreen.mainScreen().bounds.width


class StatusCell: UITableViewCell ,UICollectionViewDataSource{
    
    
     var consWidth: NSLayoutConstraint?
     var consHeight: NSLayoutConstraint?
    
    var forwardLabel: UILabel?
    
    var status: Status?{
        didSet{
            iconImage.sd_setImageWithURL(status?.user?.proFileUrl)
            memberIconView.image = status?.user?.varifiedImage
            vipIconView.image = status?.user?.mbImage
//
            nameLabel.text = status?.user?.name
            timeLabel.text = status?.created_at
            sourceLabel.text = status?.source
            contentLabel.text = status?.text
            
            forwardLabel?.text = (status?.retweeted_status?.user?.name ?? "") + ":" + (status?.retweeted_status?.text ?? "")
            
            let result = caculatePicSize(status!)
            consWidth?.constant = result.viewSize.width
            consHeight?.constant = result.viewSize.height
            pictureLayout.itemSize = result.itemSize


            //刷新配图
            pictureView.reloadData()
        }
    }
    
    //根据转发字段  返回  cellIndentifier
    class func cellIndentifier(status:Status) -> String{
        return status.retweeted_status != nil ?StatusForwardCellIndentifer :StatusNormalCellIndentifier
    }
    
    func rowHeight(status: Status) -> CGFloat{
        //设置数据
        self.status = status
        
        //刷新布局
        layoutIfNeeded()
        
        let height = CGRectGetMaxY(footerView.frame)
        //获取行高
        return  height

    }
    
    //MARK: - UICollectionViewDataSource
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.picUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellIndentifier, forIndexPath: indexPath) as! StatusPictureCell
        cell.imageUrl = status!.picUrls![indexPath.item]
        return cell
        
    }
    
    //计算图像占位大小
    private func caculatePicSize(status:Status) -> (viewSize: CGSize, itemSize: CGSize){
        
        let imageWithHeight:CGFloat = 90
        let itemSize = CGSize(width: imageWithHeight, height: imageWithHeight)
        let margin: CGFloat = 10

        
        let imageCount = status.picUrls?.count ?? 0
        
        //无图
        if  imageCount == 0{
            return (CGSizeZero,itemSize)
        }
        
        //1张
        if imageCount == 1{
            let key = status.picUrls![0].absoluteString
            let imageSize =  SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key).size
            return (imageSize,imageSize)
        }
        
        
        //4张
        if imageCount == 4{
            let w = imageWithHeight * 2 + margin
            return (CGSize(width: w, height: w),itemSize)
        }
        
        //多张
        let col = 3 //每行图片数量
        let row = (imageCount - 1) / col + 1
        
        let w = imageCount < 4 ? imageWithHeight * CGFloat(imageCount) + CGFloat(imageCount - 1) * margin : imageWithHeight * CGFloat(col) + CGFloat(col - 1) * margin

        let h = CGFloat(row) * imageWithHeight + CGFloat(row - 1) * margin
        
        return (CGSize(width: w, height: h),itemSize)
    }

    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        
        addSubview(topView)
        addSubview(iconImage)
        addSubview(memberIconView)
        addSubview(nameLabel)
        addSubview(vipIconView)
        addSubview(timeLabel)
        addSubview(sourceLabel)
        addSubview(contentLabel)
        addSubview(pictureView)
        addSubview(footerView)
        
        preparePictureView()
        
//        setupConstraint()
        

        topView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: screenWidth, height: 10))
        
        iconImage.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: 50, height: 50), offset: CGPoint(x: 12, y: 12))
        memberIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: iconImage, size: nil, offset: CGPoint(x:  5, y: 5))
        nameLabel.ff_AlignHorizontal(ff_AlignType.TopRight, referView: iconImage, size: nil, offset: CGPoint(x: 12, y: 0))
        vipIconView.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: nameLabel, size: nil, offset: CGPoint(x: 12, y: 0))
        timeLabel.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: iconImage, size: nil, offset: CGPoint(x: 12, y: 0))
        sourceLabel.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: timeLabel, size: nil, offset: CGPoint(x: 12, y: 0))
        
        contentLabel.ff_AlignVertical(ff_AlignType.BottomLeft, referView: iconImage, size: nil, offset: CGPoint(x: 0, y: 12))
        contentLabel.preferredMaxLayoutWidth = screenWidth - 12
        //加了此句不能正确显示,要用上面的这句代替
//        addConstraint(NSLayoutConstraint(item: contentLabel, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: -10))
        
        //TODO: 配图视图
//        let constranit = pictureView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: contentLabel, size: CGSize(width: 290, height: 90), offset: CGPoint(x: 0, y: 12))
//        //取出宽高约束
//        consWidth = pictureView.ff_Constraint(constranit, attribute: NSLayoutAttribute.Width)!
//        consHeight = pictureView.ff_Constraint(constranit, attribute: NSLayoutAttribute.Height)!
        
        footerView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: pictureView, size: CGSize(width: screenWidth, height: 44),offset: CGPoint(x: -12, y: 12))
        
        
        
    }
    
    //纯官方布局写的自动布局
    private func setupConstraint(){
    let screenWidth = UIScreen.mainScreen().bounds.width

        topView.translatesAutoresizingMaskIntoConstraints = false
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view1(10)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view1":topView]))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view2]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view2":topView]))
        
        iconImage.translatesAutoresizingMaskIntoConstraints = false
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-12-[view1(50)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view1":iconImage]))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-12-[view1(50)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view1":iconImage]))
        
        contentLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[view1]-12-[view2]", options: NSLayoutFormatOptions.AlignAllLeading, metrics: nil, views: ["view1":iconImage,"view2":contentLabel]))
        contentLabel.preferredMaxLayoutWidth = screenWidth - 12
        //加了此句不能正确显示,要用上面的这句代替
//        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[view1]-12-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view1":contentLabel]))
        
        pictureView.translatesAutoresizingMaskIntoConstraints = false
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[view1]-12-[view2]", options: NSLayoutFormatOptions.AlignAllLeading, metrics: nil, views: ["view1":contentLabel,"view2":pictureView]))
        consWidth = NSLayoutConstraint(item: pictureView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 0, constant: 290)
        addConstraint(consWidth!)
        
        consHeight = NSLayoutConstraint(item: pictureView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 0, constant: 90)
        addConstraint(consHeight!)
        
        footerView.translatesAutoresizingMaskIntoConstraints = false
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[view1]-12-[view2(44)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view1":pictureView,"view2":footerView]))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view1]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view1":footerView]))
        
        
        
        
    
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //准备配置视图
   private func preparePictureView(){
    pictureView.backgroundColor = UIColor.darkGrayColor()
    
    pictureView.dataSource = self
    
    pictureView.registerClass(StatusPictureCell.self, forCellWithReuseIdentifier: PictureCellIndentifier)
    
    pictureLayout.minimumInteritemSpacing = 10
    pictureLayout.minimumLineSpacing = 10
    }
    
    // MARK: - 懒加载数据
    lazy var topView: UIView = {
       let v = UIView()
        
        v.backgroundColor = UIColor.darkGrayColor()
        
        return v
    }()
    lazy var iconImage = UIImageView()
    lazy var memberIconView: UIImageView = UIImageView(image: UIImage(named: "avatar_grassroot"))
    lazy var vipIconView: UIImageView = UIImageView(image: UIImage(named:"common_icon_membership_level1"))
    lazy var nameLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 14)
    lazy var timeLabel:UILabel = UILabel(color: UIColor.orangeColor(), fontSize: 10)
    lazy var sourceLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 10)
    lazy var contentLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 15, mutiLines: true)
  
    lazy var pictureLayout = UICollectionViewFlowLayout()
    lazy var pictureView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.pictureLayout)
    
     lazy var footerView: FooterView = FooterView()
}

//MARK: - 配图的cell
private class StatusPictureCell: UICollectionViewCell{
    
    var imageUrl:NSURL?{
        didSet{
            //如果缓存中有图片,从缓存中加载,没有就从网络加载
            iconImageView.sd_setImageWithURL(imageUrl)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(iconImageView)
        iconImageView.ff_Fill(self)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var iconImageView: UIImageView = {
        let icon = UIImageView()
        
        icon.contentMode = UIViewContentMode.ScaleAspectFill
        icon.clipsToBounds = true
        
        return icon
    }()
}

//MARK: - 页脚的视图
 class FooterView: UIView{
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        addSubview(forward)
        addSubview(comment)
        addSubview(likeBtn)
        
        ff_HorizontalTile([forward,comment,likeBtn], insets: UIEdgeInsetsZero)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    lazy var forward: UIButton = UIButton(title: "转发", imageName: "timeline_icon_retweet", fontSize: 12)
    lazy var comment: UIButton = UIButton(title: "评论", imageName: "timeline_icon_comment", fontSize: 12)
    lazy var likeBtn: UIButton = UIButton(title: "点赞", imageName: "timeline_icon_unlike", fontSize: 12)
}
